package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderBillDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderBillEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderBillDetailService;
import com.atguigu.gulimall.ware.service.WareOrderBillService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
@RabbitListener(queues = {"stock.release.stock.queue"})
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private ProductFeignService  productFeignService;
    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private WareOrderBillDetailService wareOrderBillDetailService;
    @Resource
    private WareOrderBillService wareOrderBillService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty((String) params.get("skuId"))) {
            wrapper.eq("sku_id", params.get("skuId"));
        }
        if (StringUtils.isNotEmpty((String) params.get("wareId"))) {
            wrapper.eq("ware_id", params.get("wareId"));
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 判断如果没有该条库存记录，则新增，否则，更新
        List<WareSkuEntity> list = this.list(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(list)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // 远程查询sku的name，如果失败，无需回滚
            try {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.save(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = this.baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            if (count != null && count > 0) {
                vo.setHasStock(true);
            } else {
                vo.setHasStock(false);
            }

            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     *
     * 默认只要是运行时异常，都会回滚
     *
     * 库存解锁的场景：
     *      1.下订单成功，订单过期没有支付系统自动取消；被用户手动取消，都要解锁
     *      2.下订单成功，库存锁定成功，但是接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     *
     * @param wareSkuLockVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        /**
         * 保存库存工作单详情
         * 为了追溯
         */
        WareOrderBillEntity taskEntity = new WareOrderBillEntity();
        taskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderBillService.save(taskEntity);


        // 1.按照下单的收货地址，找到一个就近仓库，锁定库存
        // 1.找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> list = locks.stream().map(lock -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = lock.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(lock.getCount());
            // 查询该商品在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        // 2.锁定库存
        Boolean allLock = true;
        for (SkuWareHasStock skuWareHasStock : list) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            /**
             * 1.如果每一个商品都锁定成功， 将当前商品锁定了几件的工作单记录发给mq
             * 2.锁定失败，前面保存的工作单信息就回滚了，发送出去的消息即使要解锁记录，由于去数据库查不到id，所以就不用解锁
             */
            for (Long wareId : wareIds) {
                Long rowCount = this.baseMapper.lockSkuStock(skuId, wareId, skuWareHasStock.getNum());
                if (rowCount == 1) {
                    // 成功
                    skuStocked = true;
                    // 告诉mq库存锁定成功，触发自动解锁功能
                    WareOrderBillDetailEntity taskDetailEntity = new WareOrderBillDetailEntity();
                    taskDetailEntity.setSkuId(skuId);
                    taskDetailEntity.setSkuNum(skuWareHasStock.getNum());
                    taskDetailEntity.setTaskId(taskEntity.getId());
                    taskDetailEntity.setWareId(wareId);
                    taskDetailEntity.setLockStatus(1);
                    wareOrderBillDetailService.save(taskDetailEntity);
                    // rabbitmq
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo detail = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, detail);
                    // 防止回滚以后找不到数据
                    stockLockedTo.setDetail(detail);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                } else {
                    // 当前仓库锁失败了，重试下一个仓库
                }
            }
            if (!skuStocked) {
                throw new NoStockException(skuId);
            }
        }
        // 肯定全部都是锁定成功的
        return allLock;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

    @Override
    public void unlockStock(StockLockedTo to) throws IOException {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        // 1.查询数据库关于这个订单锁定库存的信息
        // 有，证明库存是锁定成功，但是到底要不要解锁，还需要看订单情况
        //      没有这个订单，必须解锁
        //      有这个订单，要看订单状态，如果是已取消，就解锁；只要没取消，就不能解锁库存
        WareOrderBillDetailEntity byId = wareOrderBillDetailService.getById(detailId);
        if (byId != null) {
            Long id = to.getId(); // 库存工作单的id
            WareOrderBillEntity taskEntity = wareOrderBillService.getById(id);
            String orderSn = taskEntity.getOrderSn(); // 订单号
            // 远程查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {});
                if (orderVo == null || orderVo.getStatus() == 4) {
                    // 解锁
                    if (byId.getLockStatus() == 1) {
                        this.unlockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 消息拒绝之后重新放入队列，让别人继续消费解锁
                throw new RuntimeException();
            }
        }
    }

    /**
     * 解锁订单，防止解锁订单服务卡顿，导致订单状态一直无法修改，库存消息优先到期，结果查询订单状态为新建状态，什么都不走就消费了
     * 导致当前卡顿的订单永远不能解锁库存s
     */
    @Override
    @Transactional
    public void unlockStock(OrderTo to) throws IOException {
        String orderSn = to.getOrderSn();
        // 查询库存状态，防止重复解锁
        WareOrderBillEntity taskEntity = wareOrderBillService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        // 按照工作单，找到所有没有解锁的库存，进行解锁
        List<WareOrderBillDetailEntity> entities = wareOrderBillDetailService.list(new QueryWrapper<WareOrderBillDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        for (WareOrderBillDetailEntity entity : entities) {
            this.unlockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    /**
     * 解锁库存
     */
    private void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        this.baseMapper.unlockStock(skuId, wareId, num);
        // 更新库存工作单的状态，变为已解锁
        WareOrderBillDetailEntity detailEntity = new WareOrderBillDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);
        wareOrderBillDetailService.updateById(detailEntity);
    }

}